package org.acmclass.fatworm.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Config {

	private static Map<String, String> map;

	public static void load(String filename) throws IOException {
		BufferedReader reader = new BufferedReader(new FileReader(filename));
		map = new HashMap<String, String>();
		String line;
		while ((line = reader.readLine()) != null) {
			if (line.startsWith("#"))
				continue;
			parseLine(line);
		}
		reader.close();
	}

	private static void parseLine(String line) {
		if (line.trim().equals(""))
			return;
		if (line.contains("=")) {
			String[] tokens = line.split("=");
			if (tokens.length == 2) {
				String key = tokens[0].trim();
				String value = tokens[1].trim();
				if (checkToken(key) && checkToken(value)) {
					map.put(key, value);
					return;
				}
			}
		}
		System.err.println("[Config] line not parsable: ".concat(line));
	}

	private static boolean checkToken(String token) {
		return token.matches("[^\\s]+");
	}

	public static String get(String key) {
		return map.get(key);
	}

	public static String get(String key, String defaultValue) {
		if (map.containsKey(key))
			return map.get(key);
		else
			return defaultValue;
	}

	public static Boolean getBoolean(String key, boolean defaultValue) {
		String ret = get(key);
		if (ret.equalsIgnoreCase("true"))
			return Boolean.TRUE;
		else if (ret.equalsIgnoreCase("false"))
			return Boolean.FALSE;
		else
			return defaultValue;
	}
}
